<?php
/**
 * Constants file edit utilite
 * 
 * Project: LanguageTranslation<br/>
 * File: index.php
 * 
 */

// Messages constants
define('MESSAGE_SAVED_SUCCESSFULLY', 1);
define('MESSAGE_CREATED_FILE', 2);
define('MESSAGE_RELOADED_FILE', 3); 



include "adm_header.php";
require_once 'lang_file_editor/include/common.php';
writeCommonAdminTable("Language Editor",1);

// Prepare access objects
$oTemplate = new Template();

// Retrieve parameters
$sAction = isset($_REQUEST['act']) ? $_REQUEST['act'] : null;
$sFilter = isset($_REQUEST['filter']) ? $_REQUEST['filter'] : null;

$sCurrentUrl  = Http::getCurrentPageUrl();

// Means redirection to define the current URL more extactly
// according to the saved parameters
$bFixedUrl = false;

// File name 
$aListFile = getLanguageConstFiles();
if (!isset($_REQUEST['filename'])) {
	if (!isset($_SESSION['FileEditor/sFilename'])) {
		$sCurrentUrl = Http::addUrlParameter($sCurrentUrl, 'filename', $aListFile[0]);
	} else {
		$sCurrentUrl = Http::addUrlParameter($sCurrentUrl, 'filename', $_SESSION['FileEditor/sFilename']);
	}
	$bFixedUrl = true;
} else {
	$sFileName = $_REQUEST['filename'];
	$_SESSION['FileEditor/sFilename'] = $sFileName;
	unset($_SESSION['FileEditor/iPage']);
	$sCurrentUrl = Http::addUrlParameter($sCurrentUrl, 'filename', $sFileName);
}

// Current page
if (!isset($_REQUEST['page'])) {
	if (!isset($_SESSION['FileEditor/iPage'])) {
		$sCurrentUrl = Http::addUrlParameter($sCurrentUrl, 'page', 1);
	} else {
		$sCurrentUrl = Http::addUrlParameter($sCurrentUrl, 'page', $_SESSION['FileEditor/iPage']);
	}
	$bFixedUrl = true;
} else {
	$iCurrentPage = $_REQUEST['page'];
	$_SESSION['FileEditor/iPage'] = $iCurrentPage;
	$sCurrentUrl = Http::addUrlParameter($sCurrentUrl, 'page', $iCurrentPage);
}

// Filter
if (isset($sFilter))  $sCurrentUrl = Http::addUrlParameter($sCurrentUrl, 'filter', $sFilter);

// Make the current URL more exact
if ($bFixedUrl) {
	Http::redirect_user($sCurrentUrl);
}


$set_htmltags_allowed="br,p,b,i,a,img,ol,li,ul";
$lTagsAllowed = explode(',', $set_htmltags_allowed);
for ($i = 0; $i < count($lTagsAllowed); $i++) $lTagsAllowed[$i] = trim($lTagsAllowed[$i]);

$set_htmlattribs_allowed="href,type";
$lAttrAllowed = explode(',',$set_htmlattribs_allowed);
for ($i = 0; $i < count($lAttrAllowed); $i++) $lAttrAllowed[$i] = trim($lAttrAllowed[$i]);
	


$sCurLanguage = substr($sFileName, 0, 3);
if ($sCurLanguage=="adm")
	$sCurLanguage = "adm_" . substr($sFileName, 4, 3);

// User and System file names
$sSystemFileName = PATH_SYSTEM_FILES.'/'.$sFileName;
$sUserFileName = PATH_USER_FILES.'/'.$sCurLanguage.USER_FILE_NAME;

// Do actions
switch ($sAction) {
	case 'Save':
		saveLanguageInSession($sCurLanguage);
		$_SESSION["iMessage"] = MESSAGE_SAVED_SUCCESSFULLY;
		Http::redirect_user($sCurrentUrl);
		break;

	case 'GenerateFile':
		@unlink("config/cache/getExtraForm.cache");
		@unlink("config/cache/getExtraOptionsForm.cache");
		saveLanguageInSession($sCurLanguage);
		$sFileNameUser = PATH_USER_FILES.'/'.$sCurLanguage.USER_FILE_NAME;

		ksort($_SESSION[$sCurLanguage]['constant']);

		// Write constants to file
		$sFileContent = "<?php\n";
		$sFileContent.="\$lang_version='$lang_version';\n";
		$sFileContent.="\$lang_date='$lang_date';\n";
		foreach ($_SESSION[$sCurLanguage]['constant'] as $key=>$value) {
			if (!empty($value)) {
				 $sFileContent .= "define(".var_export($key, true).",".var_export(makeLineBreaksFromCRLF($value), true).");\n";
			}
		}
		$sFileContent .= "?>";

		
		$rFile = fopen($sFileNameUser, 'wb');
		if (!WA())
		{
			echo "<b>Demo-mode</b><br>System in demo-mode, no configuration saved!<br>";	
		}
		else 
		{
			fputs($rFile,$sFileContent);
		}
		fclose($rFile);
		chmod($sFileNameUser,octdec($set_chmod));

		$_SESSION["iMessage"] = MESSAGE_CREATED_FILE;
		Http::redirect_user($sCurrentUrl);
		break;

	case 'AddConstant':
		$_SESSION[$sCurLanguage]['constant'][$_REQUEST['constant_name']] = $_REQUEST['constant_name'];
		$iCurrentPage = 1;
		Http::redirect_user($sCurrentUrl);
		break;
		
	case 'Reload': 
		unset($_SESSION[$sCurLanguage]['constant']); 
		$_SESSION["iMessage"] = MESSAGE_RELOADED_FILE; Http::redirect_user($sCurrentUrl, 'act'); 
		break; 
}

// System constants to array
$aSystemConstantAndValue = getConstantAndValues($sSystemFileName);

// User constants to session
if (empty($_SESSION[$sCurLanguage]['constant'])) {
	$_SESSION[$sCurLanguage]['constant'] = getConstantAndValues($sUserFileName);
}

// Add new constants from user to system array
if (!empty($_SESSION[$sCurLanguage]['constant'])) {
	foreach ($_SESSION[$sCurLanguage]['constant'] as $constantName => $constantValue) {
		if (!array_key_exists($constantName, $aSystemConstantAndValue)) {
			$aSystemConstantAndValue[$constantName] = $constantName;
		}
	}
}

// Sort system arrays
ksort($aSystemConstantAndValue);


// Applay filter (if exist)
if (!empty($sFilter)) {
	foreach ($aSystemConstantAndValue as $sConstantName => $sConstantValue) {
		if (!strstr(strtolower($sConstantName), strtolower($sFilter))
		    && !strstr(strtolower($sConstantValue), strtolower($sFilter))
		) {
			unset($aSystemConstantAndValue[$sConstantName]);
		}
	}
}

// Pager operations
$aResultArray = array();
$i = 0;

$iConstantCount = count($aSystemConstantAndValue);
$iPageSize = VIEW_CONSTANT_ROW_NUM;
$iPageCount = ceil($iConstantCount / $iPageSize);

foreach ($aSystemConstantAndValue as $constantName => $constantValue) {
	if ($i>=$iCurrentPage * VIEW_CONSTANT_ROW_NUM) break;

	if ($i>=($iCurrentPage-1) * VIEW_CONSTANT_ROW_NUM) {
		$aResultArray[] = array($constantName, $aSystemConstantAndValue[$constantName], $_SESSION[$sCurLanguage]['constant'][$constantName]);
	}
	$i++;
}

// Display page
$oTemplate->assign(array(
    'sAction'       => $sAction,
    'iCurrentPage'  => $iCurrentPage,
    'iPageCount'    => $iPageCount,
    'sCurrentUrl'   => $sCurrentUrl,
    'sFilter'       => $sFilter,
    'sCurFileName'  => $sFileName,
    'sCurLanguage'  => $sCurLanguage,
    'sCurrentUrl'   => $sCurrentUrl,
));


$oTemplate->assignByRef('aResultArray', $aResultArray);
$oTemplate->assignByRef('aConstantValue', $_SESSION[$sCurLanguage]['constant']);
$oTemplate->assignByRef('aListFile', $aListFile);
$oTemplate->display(PATH_TEMPLATES."/index.tpl.php");

// Unset old messages
if (isset($_SESSION["iMessage"])) unset($_SESSION["iMessage"]);
if (isset($_SESSION["iError"])) unset($_SESSION["iError"]);

function getLanguageConstFiles() {
	// Get list of language constant files
	$aListFile = array();
	$sDirPath = PATH_SYSTEM_FILES;
	if ($dirHandle = opendir($sDirPath)) {
		while (($sFile = readdir($dirHandle)) !== false) {
			if (is_file($sDirPath.'/'.$sFile)) {
				$sType = substr($sFile, -(strlen(SYSTEM_FILE_NAME)));
				if ($sType == SYSTEM_FILE_NAME) {
					$aListFile[] = $sFile;
				}
			}
		}
		closedir($dirHandle);
	}
	return $aListFile;
}



function saveLanguageInSession($sCurLanguage) {
	$sSessionName = "constant_".$sCurLanguage;
	foreach ($_REQUEST['constant'] as $key => $value) {
		if (!empty($value)) {
			$_SESSION[$sCurLanguage]['constant'][$key] = $value;
		}
		elseif (isset($_SESSION[$sCurLanguage]['constant'][$key])) {
			unset($_SESSION[$sCurLanguage]['constant'][$key]);
		}
	}
}
writeCommonAdminTable("Language Editor","");
include "adm_footer.php";

?>